package org.reference.generic.work;

import org.reference.generic.base.Item;
import org.reference.generic.base.Manager;
import org.reference.generic.base.Parameter;

/**
 * 
 */
public class MachineManager extends Manager implements Machine.OnCompleteListenner {

    /**
     * 
     */
    public MachineManager() {
    	setName("MACHINE_MANAGER");
    }

    private long cmax;
    private Schedule schedule;

    /**
     * @param schedule
     */
    public void run(Schedule schedule) {
    	this.schedule = schedule;
    	for (Item machine : itemList) {
    		if (schedule.isAvailable())
    			((Machine) machine).run(schedule.getNextJob());
    	}
    }

    /**
     * @return
     */
    public double getCMAX() {
    	double result_cmac = cmax;
        return (double)(result_cmac / 1000*60);
    }

	@Override
	public void init(Parameter[] parameters) {
		for (Parameter param: parameters) {
			if(param.getName().equalsIgnoreCase(Parameter.TYPE_MACHINE_NUMBER)) {  // Machine 갯수 만큼 생성... 
				for(int i=0 ; i<param.getValueToInt(); i++){
				Machine machine = new Machine();
				machine.setOnCompleteListenner(this); 
				itemList.add(machine);
				}
			}
			
//			if(param.getName().equalsIgnoreCase(Parameter.TYPE_MACHINE_STEP)) {
//				Machine machine = new Machine();
//				machine.setStep(param.getValueToInt());
//				machine.setOnCompleteListenner(this);   //머신 oncomleteListenner에 machine manager를 넣음.
//				itemList.add(machine);
//				}
			}
		}
	

	@Override
	public Parameter[] getResult() {
		return null;
	}

	@Override
	public void onComplete(Machine machine) {
		if (schedule.isAvailable()) {
			machine.run(schedule.getNextJob());
		} else {
			for (Item item : itemList) {				// 아이템 리스트에서 첫번째 부터 아이템에 넣고 처리함... 
				if (((Machine) item).isBusy()) {
					cmax = 0;
					return;
				}   // machine busy를 통해서 모든 작업이 완료 된것을 확인.
				
			}
			cmax = machine.getWorkingTime();
			onComplete();
		}		
	}

}